package com.kajespero.utils;

import java.io.Serializable;
import java.lang.reflect.Field;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Transaction;

import com.kajespero.vo.IdentifierVO;

public class PersistManagerJdoHelper {
	
	private static final PersistenceManagerFactory INSTANCE = JDOHelper.getPersistenceManagerFactory("transactions-optional");
	
	private static final PersistenceManager PERSISTENCE_MANAGER = getInstance().getPersistenceManager();
	
	public static PersistenceManagerFactory getInstance(){
		return INSTANCE;
	}
	
	public static PersistenceManager getPersistenceManager(){
		return PERSISTENCE_MANAGER;
	}

	public static <T extends IdentifierVO<?>> Object saveOrUpdate(T instance){
		return save(instance);
	}
	
	public static <T extends Serializable> void delete(T instance){
		Transaction transaction = getPersistenceManager().currentTransaction();
		transaction.begin();
		getPersistenceManager().deletePersistent(instance);
		transaction.commit();
		
	}
	
	public static <T extends Serializable> T refesh(T instance){
		Transaction transaction = getPersistenceManager().currentTransaction();
		transaction.begin();
		getPersistenceManager().refresh(instance);
		transaction.commit();
		return instance;
	}
	
	
	private static <T extends Serializable> Object save(T instance){
		Transaction transaction = getPersistenceManager().currentTransaction();
		transaction.begin();
		
		getPersistenceManager().makePersistent(instance);
		transaction.commit();
		return instance;
	}
	
	@Deprecated
	public static <T extends Serializable> void update(T oldInstance, T newInstance){
		if(oldInstance.getClass().getName().equals(newInstance.getClass().getName())){
			Field [] fields  = oldInstance.getClass().getDeclaredFields();
			for(Field field : fields ){
				field.setAccessible(true);
				if(field.isAccessible()){
					try {
						Object newValue = field.get(newInstance);
						field.set(oldInstance, newValue);
					} catch (IllegalArgumentException e) {
						
					} catch (IllegalAccessException e) {
					
					}
				}
			}
		}
	}
	

}
